// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2024-07-10

package resource

import (
	"encoding/json"
	"gitee.com/go-libs/config/src/common"
	"gopkg.in/yaml.v3"
	"os"
	"reflect"
)

const NotfoundResource = Resource("")

// Resource
// is a type name for configuration file.
//
//   f := config.Resource("./config/app.yaml")
//   f := config.Resource("/data/sketch/config/app.yaml")
type Resource string

// Found
// return true if resource is existed.
func (o Resource) Found() bool {
	return o != NotfoundResource
}

// Notfound
// return true if resource is empty.
func (o Resource) Notfound() bool {
	return o == NotfoundResource
}

// Read
// reads resource content.
func (o Resource) Read() (data []byte, err error) {
	if o.Found() {
		data, err = os.ReadFile(o.String())
	}
	return
}

// ScanJson
// scans resource content of json to v.
func (o Resource) ScanJson(v any) (err error) {
	var data []byte

	// After scan.
	defer func() {
		if x, ok := v.(AfterScanner); ok {
			x.After()
		}
	}()

	// Before scan.
	if x, ok := v.(BeforeScanner); ok {
		x.Before()
	}

	// Read and unmarshal.
	if data, err = o.ready(v); err == nil {
		err = json.Unmarshal(data, v)
	}
	return
}

// ScanYaml
// scans resource content of yaml to v.
func (o Resource) ScanYaml(v any) (err error) {
	var data []byte

	// After scan.
	defer func() {
		if x, ok := v.(AfterScanner); ok {
			x.After()
		}
	}()

	// Before scan.
	if x, ok := v.(BeforeScanner); ok {
		x.Before()
	}

	// Read and unmarshal.
	if data, err = o.ready(v); err == nil {
		err = yaml.Unmarshal(data, v)
	}
	return
}

// String
// return resource name.
//
//   return "/data/sketch/config/app.yaml"
func (o Resource) String() string {
	return string(o)
}

// +---------------------------------------------------------------------------+
// | Access methods                                                            |
// +---------------------------------------------------------------------------+

func (o Resource) ready(v any) (data []byte, err error) {
	ref := reflect.TypeOf(v)

	// Return
	// error if passed target v is not pointer.
	if ref.Kind() != reflect.Pointer || ref.Elem().Kind() != reflect.Struct {
		err = common.ErrTargetMustBePointerStruct
		return
	}

	// Read
	// resource content.
	data, err = o.Read()
	return
}
